﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace OPCTreeMonitor.SQLdb.Infrastructure
{
    public class RepositoryBase<TEntity> : IRepository<TEntity> where TEntity : class, new()
    {
        private readonly SqlSugarClient _db;

        public RepositoryBase(SqlSugarClient db)
        {
            _db = db;
        }

        #region 查询实现
        public TEntity GetById(object id) => _db.Queryable<TEntity>().InSingle(id);

        public List<TEntity> GetAll() => _db.Queryable<TEntity>().ToList();

        public List<TEntity> Where(Expression<Func<TEntity, bool>> expression) =>
            _db.Queryable<TEntity>().Where(expression).ToList();
        #endregion

        #region 增删改实现
        public bool Insert(TEntity entity) => _db.Insertable(entity).ExecuteCommand() > 0;

        public bool Update(TEntity entity) => _db.Updateable(entity).ExecuteCommand() > 0;

        public bool Delete(TEntity entity) => _db.Deleteable(entity).ExecuteCommand() > 0;
        #endregion

        #region 批量操作实现
        public int InsertRange(List<TEntity> entities) => _db.Insertable(entities).ExecuteCommand();

        public int UpdateRange(List<TEntity> entities) => _db.Updateable(entities).ExecuteCommand();

        public int DeleteRange(List<TEntity> entities) => _db.Deleteable(entities).ExecuteCommand();
        #endregion

        #region 异步操作实现
        public async Task<TEntity> GetByIdAsync(object id) => await _db.Queryable<TEntity>().InSingleAsync(id);

        public async Task<List<TEntity>> GetAllAsync() => await _db.Queryable<TEntity>().ToListAsync();

        public async Task<int> InsertAsync(TEntity entity) => await _db.Insertable(entity).ExecuteCommandAsync();

        public async Task<int> UpdateAsync(TEntity entity) => await _db.Updateable(entity).ExecuteCommandAsync();

        public async Task<int> DeleteAsync(TEntity entity) => await _db.Deleteable(entity).ExecuteCommandAsync();
        #endregion

        #region 扩展修改实现
        public bool Update(TEntity entity, Expression<Func<TEntity, object>> columns) =>
            _db.Updateable(entity).UpdateColumns(columns).ExecuteCommand() > 0;
        #endregion

        
        public SqlSugarClient GetDbClient()
        {
            return _db; // 返回注入的SqlSugarClient实例
        }
    }
}
